package com.sihan.swvp.filter;

import java.util.Properties;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.scripting.xmltags.DynamicContext;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;


@SuppressWarnings("all")
@Intercepts({  
    @Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }),  
    @Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class,  
            RowBounds.class, ResultHandler.class }) })  
//@Intercepts(@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}))
public class SqlPlugins implements Interceptor{

	Logger log = Logger.getLogger(SqlPlugins.class);
	@Override
	public Object intercept(Invocation invocation) throws Throwable {
		final Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        Object parameterObject = args[1];
		BoundSql boundSql = ms.getBoundSql(parameterObject);
		log.info("Function: "+ms.getId());
		log.info("Execute sql: \n"+boundSql.getSql());
		System.out.println("Execute sql: "+boundSql.getSql().replaceAll("(\r\n|\r|\n|\n\r)", " "));
		log.info("Parameter Mappings: "+boundSql.getParameterMappings());
		log.info("Parameter Object: "+JSON.toJSONString(boundSql.getParameterObject()));
		System.out.println("Parameter Object: "+JSON.toJSONString(boundSql.getParameterObject()));
		
		return invocation.proceed();
	}

	
	@Override
	public Object plugin(Object target) {
		if (target instanceof Executor) {

			return Plugin.wrap(target, this);
		} else {
			return target;
		}
	}

	@Override
	public void setProperties(Properties properties) {
		// TODO Auto-generated method stub
		
	}

}
